package com.manytory.torylotto.data;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class DataHandler extends DefaultHandler {
	private String elementValue = null;
    private Boolean elementOn = false;
    private ResultCodeGetSet resCode = null;
    private InningDataGetSet inningData = null;
    private ArrayList<NewsDataGetSet> newsList = new ArrayList<NewsDataGetSet>();
    private NewsDataGetSet newsData = null;
    
    public ArrayList<NewsDataGetSet> getNewsData() {
    	return newsList;
    }
    
    public InningDataGetSet getInningData() {
    	return inningData;
    }
    
    public ResultCodeGetSet getResultCode() {
    	return resCode;
    }

	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
	}
    
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		elementOn = true;

		if(localName.equals("rtncode")) {
			resCode = new ResultCodeGetSet();
		}
		
		if(localName.equals("inning")) {
			inningData = new InningDataGetSet();
		}

		if(localName.equals("news")) {
			newsData = new NewsDataGetSet();
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		elementOn = false;
		
		if(localName.equalsIgnoreCase("rtncode")) {
			resCode.setResultCode(Integer.parseInt(elementValue));
		} else if(localName.equalsIgnoreCase("th")) {
			inningData.setTH(Integer.parseInt(elementValue));
		} else if(localName.equalsIgnoreCase("sum")) {
			inningData.setSum(Double.parseDouble(elementValue));
		} else if(localName.equalsIgnoreCase("cldate")) {
			inningData.setDate(elementValue);
		} else if(localName.equalsIgnoreCase("idx")) {
			newsData.setIdx(Integer.parseInt(elementValue));
		} else if(localName.equalsIgnoreCase("title")) {
			newsData.setTitle(elementValue);
		} else if(localName.equalsIgnoreCase("body")) {
			newsData.setContent(elementValue);
		} else if(localName.equalsIgnoreCase("date")) {
			newsData.setDate(elementValue);
		} else if(localName.equalsIgnoreCase("news")) {
			newsList.add(newsData);
			newsData = null;
		}
	}
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if (elementOn) {
            elementValue = new String(ch, start, length);
            elementOn = false;
        }
	}
}
